package com.infore.common.fw;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.infore.common.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * @ControllerAdvice 和 @RestControllerAdvice都是对Controller和RestController进行增强
 */
@Slf4j
@RestControllerAdvice
public class BaseController extends BusinessExceptionHandler{
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

     //线程不安全
//    protected Page<Object> page;
    protected  ThreadLocal<Page> page = new ThreadLocal<>();

    /**
     * 分页参数提取
     *
     * @param request
     */
    protected void startPage(CriterionRequest request) {
        page.set(PageHelper.startPage(request.getPage(), request.getLimit(), request.orderBy()));
    }

    protected void startPage(CriterionRequest request, Class<?> entityClass) {
        page.set(PageHelper.startPage(request.getPage(), request.getLimit(), PageUtils.buildOrderTo(request, entityClass)));
    }
    protected PageRequest buildPageRequest(CriterionRequest request) {
        return PageUtils.buildPageRequest(request);
    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false  ));
    }



}
